/**
 * 主JavaScript文件
 * 提供通用的功能和工具函数
 */

// 全局配置
const CONFIG = {
    // API基础路径
    API_BASE_URL: '/',
    // 表单验证配置
    VALIDATION: {
        phoneRegex: /^1[3-9]\d{9}$|^0\d{2,3}-\d{7,8}$/,
        emailRegex: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
    }
};

// 工具函数对象
const Utils = {
    /**
     * 显示提示消息
     * @param {string} message 消息内容
     * @param {string} type 消息类型 (success, error, info)
     * @param {number} duration 持续时间(毫秒)
     */
    showMessage: function(message, type = 'info', duration = 3000) {
        // 检查是否已存在消息容器
        let messageContainer = document.getElementById('messageContainer');
        if (!messageContainer) {
            messageContainer = document.createElement('div');
            messageContainer.id = 'messageContainer';
            messageContainer.className = 'message-container';
            document.body.appendChild(messageContainer);
        }
        
        // 创建消息元素
        const messageElement = document.createElement('div');
        messageElement.className = `message message-${type}`;
        messageElement.textContent = message;
        
        // 添加到容器
        messageContainer.appendChild(messageElement);
        
        // 显示消息
        setTimeout(() => {
            messageElement.style.opacity = '1';
        }, 10);
        
        // 自动关闭
        setTimeout(() => {
            messageElement.style.opacity = '0';
            setTimeout(() => {
                messageContainer.removeChild(messageElement);
            }, 300);
        }, duration);
    },
    
    /**
     * 表单验证
     * @param {HTMLFormElement} form 表单元素
     * @returns {object} { isValid: boolean, errors: array }
     */
    validateForm: function(form) {
        const errors = [];
        const requiredFields = form.querySelectorAll('[required]');
        
        // 验证必填字段
        requiredFields.forEach(field => {
            if (!field.value.trim()) {
                const label = form.querySelector(`label[for="${field.id}"]`);
                const fieldName = label ? label.textContent.replace('*', '').trim() : field.name;
                errors.push(`${fieldName}是必填字段`);
            }
        });
        
        // 验证手机号
        const phoneFields = form.querySelectorAll('input[type="tel"], input[name="phone"]');
        phoneFields.forEach(field => {
            if (field.value.trim() && !CONFIG.VALIDATION.phoneRegex.test(field.value.trim())) {
                errors.push('请输入有效的手机号码');
            }
        });
        
        // 验证邮箱
        const emailFields = form.querySelectorAll('input[type="email"], input[name="email"]');
        emailFields.forEach(field => {
            if (field.value.trim() && !CONFIG.VALIDATION.emailRegex.test(field.value.trim())) {
                errors.push('请输入有效的邮箱地址');
            }
        });
        
        return {
            isValid: errors.length === 0,
            errors: errors
        };
    },
    
    /**
     * 发送AJAX请求
     * @param {string} url 请求URL
     * @param {string} method 请求方法
     * @param {object} data 请求数据
     * @param {function} successCallback 成功回调
     * @param {function} errorCallback 错误回调
     */
    ajax: function(url, method, data, successCallback, errorCallback) {
        // 显示加载中
        this.showLoading();
        
        // 添加CSRF token支持（已移除，简化处理）
        // 注意：生产环境中建议启用CSRF保护
        
        $.ajax({
            url: url,
            type: method,
            data: data,
            dataType: 'json',
            success: (res) => {
                this.hideLoading();
                if (successCallback) {
                    successCallback(res);
                }
            },
            error: (xhr, status, error) => {
                this.hideLoading();
                // 显示错误消息
                this.showMessage('网络请求失败，请稍后重试', 'error');
                if (errorCallback) {
                    errorCallback(xhr, status, error);
                }
            }
        });
    },
    
    /**
     * 显示加载中状态
     */
    showLoading: function() {
        // 检查是否已存在加载中元素
        let loadingElement = document.getElementById('loading');
        if (!loadingElement) {
            loadingElement = document.createElement('div');
            loadingElement.id = 'loading';
            loadingElement.className = 'loading';
            loadingElement.innerHTML = '<div class="loading-spinner"></div><div class="loading-text">加载中...</div>';
            document.body.appendChild(loadingElement);
        }
        
        loadingElement.style.display = 'flex';
    },
    
    /**
     * 隐藏加载中状态
     */
    hideLoading: function() {
        const loadingElement = document.getElementById('loading');
        if (loadingElement) {
            loadingElement.style.display = 'none';
        }
    },
    
    /**
     * 获取URL参数
     * @param {string} name 参数名
     * @returns {string|null} 参数值
     */
    getUrlParam: function(name) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(name);
    },
    
    /**
     * 防抖函数
     * @param {function} func 要执行的函数
     * @param {number} delay 延迟时间(毫秒)
     * @returns {function} 防抖处理后的函数
     */
    debounce: function(func, delay) {
        let timeoutId;
        return function(...args) {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(() => func.apply(this, args), delay);
        };
    },
    
    /**
     * 节流函数
     * @param {function} func 要执行的函数
     * @param {number} delay 间隔时间(毫秒)
     * @returns {function} 节流处理后的函数
     */
    throttle: function(func, delay) {
        let lastCall = 0;
        return function(...args) {
            const now = Date.now();
            if (now - lastCall >= delay) {
                lastCall = now;
                func.apply(this, args);
            }
        };
    }
};

// 为Utils添加到全局window对象，以便在其他脚本中使用
window.Utils = Utils;
window.CONFIG = CONFIG;

// 页面加载完成后的初始化
$(document).ready(function() {
    // 初始化加载样式
    initLoadingStyle();
    
    // 初始化消息提示样式
    initMessageStyle();
});

/**
 * 初始化加载样式
 */
function initLoadingStyle() {
    // 创建加载样式
    const style = document.createElement('style');
    style.textContent = `
        .loading {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.8);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            display: none;
        }
        
        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #4a90e2;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 15px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .loading-text {
            font-size: 14px;
            color: #666;
        }
    `;
    document.head.appendChild(style);
}

/**
 * 初始化消息提示样式
 */
function initMessageStyle() {
    // 创建消息提示样式
    const style = document.createElement('style');
    style.textContent = `
        .message-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 10000;
            max-width: 300px;
        }
        
        .message {
            padding: 12px 16px;
            margin-bottom: 10px;
            border-radius: 4px;
            color: white;
            font-size: 14px;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .message-success {
            background-color: #28a745;
        }
        
        .message-error {
            background-color: #dc3545;
        }
        
        .message-info {
            background-color: #17a2b8;
        }
    `;
    document.head.appendChild(style);
}

/**
 * 表单提交处理
 * @param {Event} event 事件对象
 * @param {function} submitCallback 提交回调函数
 */
function handleFormSubmit(event, submitCallback) {
    event.preventDefault();
    const form = event.target;
    
    // 验证表单
    const validationResult = Utils.validateForm(form);
    if (!validationResult.isValid) {
        // 显示错误消息
        validationResult.errors.forEach(error => {
            Utils.showMessage(error, 'error');
        });
        return;
    }
    
    // 序列化表单数据
    const formData = $(form).serialize();
    
    // 调用提交回调
    if (submitCallback) {
        submitCallback(formData);
    }
}

// 错误处理对象
const ErrorHandler = {
    /**
     * 处理AJAX错误
     */
    handleAjaxError: function(xhr, status, error) {
        let errorMessage = '操作失败，请稍后重试';
        
        if (xhr.responseJSON && xhr.responseJSON.msg) {
            errorMessage = xhr.responseJSON.msg;
        } else if (xhr.status === 404) {
            errorMessage = '请求的资源不存在';
        } else if (xhr.status === 500) {
            errorMessage = '服务器内部错误';
        } else if (xhr.status === 403) {
            errorMessage = '没有权限执行此操作';
        } else if (xhr.status === 422) {
            errorMessage = '请求参数验证失败';
        }
        
        Utils.showMessage(errorMessage, 'error');
        console.error('AJAX Error:', status, error, xhr.responseText);
    },
    
    /**
     * 处理表单验证错误
     */
    handleValidationError: function(errors) {
        if (Array.isArray(errors)) {
            errors.forEach(error => {
                Utils.showMessage(error, 'error');
            });
        } else {
            Utils.showMessage(errors, 'error');
        }
    }
};

// 将ErrorHandler添加到全局window对象
window.ErrorHandler = ErrorHandler;

// ========== 现代化通知系统 ==========
class NotificationSystem {
    constructor() {
        this.container = null;
        this.notifications = [];
        this.init();
    }
    
    init() {
        // 创建通知容器
        this.container = document.createElement('div');
        this.container.className = 'notification-container';
        document.body.appendChild(this.container);
    }
    
    show(message, type = 'info', duration = 5000, title = null) {
        const notification = this.createNotification(message, type, title);
        this.container.appendChild(notification);
        this.notifications.push(notification);
        
        // 触发显示动画
        setTimeout(() => {
            notification.classList.add('show');
        }, 10);
        
        // 自动关闭
        if (duration > 0) {
            const progressBar = notification.querySelector('.notification-progress-bar');
            if (progressBar) {
                progressBar.style.animationDuration = duration + 'ms';
            }
            
            setTimeout(() => {
                this.hide(notification);
            }, duration);
        }
        
        return notification;
    }
    
    createNotification(message, type, title) {
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        
        const icons = {
            success: '✓',
            error: '✕',
            warning: '⚠',
            info: 'ℹ'
        };
        
        const titles = {
            success: title || '成功',
            error: title || '错误',
            warning: title || '警告',
            info: title || '提示'
        };
        
        notification.innerHTML = `
            <div class="notification-icon">${icons[type] || icons.info}</div>
            <div class="notification-content">
                <div class="notification-title">${titles[type]}</div>
                <div class="notification-message">${message}</div>
            </div>
            <button class="notification-close" onclick="window.notifications.hide(this.parentElement)">×</button>
            <div class="notification-progress">
                <div class="notification-progress-bar"></div>
            </div>
        `;
        
        return notification;
    }
    
    hide(notification) {
        if (!notification || !notification.parentElement) return;
        
        notification.classList.remove('show');
        setTimeout(() => {
            if (notification.parentElement) {
                notification.parentElement.removeChild(notification);
            }
            const index = this.notifications.indexOf(notification);
            if (index > -1) {
                this.notifications.splice(index, 1);
            }
        }, 400);
    }
    
    clear() {
        this.notifications.forEach(notification => {
            this.hide(notification);
        });
    }
}

// ========== 加载管理系统 ==========
class LoadingManager {
    constructor() {
        this.overlay = null;
        this.init();
    }
    
    init() {
        // 创建加载遮罩
        this.overlay = document.createElement('div');
        this.overlay.className = 'loading-overlay';
        this.overlay.innerHTML = `
            <div class="loading-spinner"></div>
            <div class="loading-text">加载中...</div>
        `;
        document.body.appendChild(this.overlay);
    }
    
    show(text = '加载中...') {
        const textElement = this.overlay.querySelector('.loading-text');
        if (textElement) {
            textElement.textContent = text;
        }
        this.overlay.classList.add('show');
        document.body.style.overflow = 'hidden';
    }
    
    hide() {
        this.overlay.classList.remove('show');
        document.body.style.overflow = '';
    }
    
    setButtonLoading(button, loading = true, originalText = null) {
        if (loading) {
            if (!button.dataset.originalText) {
                button.dataset.originalText = button.textContent;
            }
            button.classList.add('loading');
            button.disabled = true;
            button.textContent = originalText || '处理中...';
        } else {
            button.classList.remove('loading');
            button.disabled = false;
            if (button.dataset.originalText) {
                button.textContent = button.dataset.originalText;
                delete button.dataset.originalText;
            }
        }
    }
    
    setTableLoading(table, loading = true) {
        let loadingRow = table.querySelector('.table-loading-row');
        
        if (loading) {
            if (!loadingRow) {
                const tbody = table.querySelector('tbody');
                const colCount = table.querySelectorAll('thead th').length;
                
                loadingRow = document.createElement('tr');
                loadingRow.className = 'table-loading-row';
                loadingRow.innerHTML = `
                    <td colspan="${colCount}" style="text-align: center; padding: 40px;">
                        <div class="loading-spinner" style="margin: 0 auto 15px; width: 30px; height: 30px;"></div>
                        <div>加载中...</div>
                    </td>
                `;
                
                tbody.appendChild(loadingRow);
            }
        } else {
            if (loadingRow) {
                loadingRow.remove();
            }
        }
    }
}

// 等待DOM加载完成后初始化全局实例
document.addEventListener('DOMContentLoaded', function() {
    window.notifications = new NotificationSystem();
    window.loading = new LoadingManager();
});

// 提供临时的备用函数，直到正式实例创建完成
window.notifications = {
    show: function(message, type, duration, title) {
        console.log('Notification:', message, type);
        // 临时使用alert作为备用
        if (type === 'error') {
            alert('错误: ' + message);
        } else if (type === 'success') {
            alert('成功: ' + message);
        } else {
            alert(message);
        }
    }
};

window.loading = {
    show: function(text) {
        console.log('Loading:', text);
    },
    hide: function() {
        console.log('Loading hidden');
    },
    setButtonLoading: function(button, loading, text) {
        if (loading) {
            button.disabled = true;
            button.style.opacity = '0.6';
            if (text) button.textContent = text;
        } else {
            button.disabled = false;
            button.style.opacity = '1';
        }
    }
};

// 临时便捷方法
window.showSuccess = (message, title, duration) => window.notifications.show(message, 'success', duration, title);
window.showError = (message, title, duration) => window.notifications.show(message, 'error', duration, title);
window.showWarning = (message, title, duration) => window.notifications.show(message, 'warning', duration, title);
window.showInfo = (message, title, duration) => window.notifications.show(message, 'info', duration, title);

window.showLoading = (text) => window.loading.show(text);
window.hideLoading = () => window.loading.hide();
window.setButtonLoading = (button, loading, text) => window.loading.setButtonLoading(button, loading, text);
window.setTableLoading = (table, loading) => window.loading.setTableLoading(table, loading);

// DOM加载完成后重新设置便捷方法
document.addEventListener('DOMContentLoaded', function() {
    // 重新设置便捷方法，使用正确的实例
    window.showSuccess = (message, title, duration) => window.notifications.show(message, 'success', duration, title);
    window.showError = (message, title, duration) => window.notifications.show(message, 'error', duration, title);
    window.showWarning = (message, title, duration) => window.notifications.show(message, 'warning', duration, title);
    window.showInfo = (message, title, duration) => window.notifications.show(message, 'info', duration, title);

    window.showLoading = (text) => window.loading.show(text);
    window.hideLoading = () => window.loading.hide();
    window.setButtonLoading = (button, loading, text) => window.loading.setButtonLoading(button, loading, text);
    window.setTableLoading = (table, loading) => window.loading.setTableLoading(table, loading);
});

// 更新Utils对象的showMessage方法使用新的通知系统
Utils.showMessage = function(message, type = 'info', duration = 3000) {
    window.notifications.show(message, type, duration);
};

Utils.showLoading = function() {
    window.loading.show();
};

Utils.hideLoading = function() {
    window.loading.hide();
};